package imgsm

import (
	"errors"
	"image"
	"image/jpeg"
	"image/png"
	"os"
	"path/filepath"
	"strconv"

	// https://github.com/ozankasikci/go-image-merge
	gim "github.com/ozankasikci/go-image-merge"
)

func Merge(baseDir, srcImgType, targetImgType, direction string, min, max int) error {
	srcs := make([]*gim.Grid, 0)
	for i := min; i < max; i++ {
		srcs = append(srcs, &gim.Grid{
			ImageFilePath: filepath.Join(baseDir, strconv.Itoa(i)+"."+srcImgType),
		})

	}
	/*
		grids []*gim.Grid, imageCountDX int, imageCountDY int
	*/

	var rgba *image.RGBA
	var err error

	if direction == "v" || direction == "V" {
		rgba, err = gim.New(srcs, 1, max-1).Merge()
		if err != nil {

			return err
		}
	} else if direction == "h" || direction == "H" {
		rgba, err = gim.New(srcs, max-1, 1).Merge()
		if err != nil {

			return err
		}
	}

	if rgba == nil {
		return errors.New("Merge:not support merge type")
	}

	//创建或截断命名文件。如果文件已存在，则将其截断
	targetFile, err := os.Create(filepath.Join(baseDir, "merged."+targetImgType))
	if err != nil {
		return err
	}
	defer targetFile.Close()
	if targetImgType == "jpg" {
		err = jpeg.Encode(targetFile, rgba, &jpeg.Options{Quality: 80})
	} else {
		err = png.Encode(targetFile, rgba)
	}

	if err != nil {

		return err
	}
	return nil
}
